<template>
  <div class="interface-management">
    <n-space vertical>
      <!-- 搜索和筛选条件 -->
      <n-card>
        <n-space>
          <n-input v-model="searchQuery" placeholder="搜索接口名称或URL" style="width: 300px" />
          <n-select
            v-model="filters.status"
            :options="statusOptions"
            placeholder="选择接口状态"
            style="width: 150px"
          />
          <n-select
            v-model="filters.creator"
            :options="creatorOptions"
            placeholder="选择创建者"
            style="width: 150px"
          />
          <n-button type="primary" @click="fetchInterfaceData">搜索</n-button>
          <n-button @click="resetFilters">重置</n-button>
          <n-button type="info" @click="uploadInterface">上传接口</n-button>
        </n-space>
      </n-card>

      <!-- 接口数据列表 -->
      <n-data-table :columns="columns" :data="interfaceData.records" :loading="loading" />
      <!--      <n-pagination-->
      <!--        v-model:page="pagination.page"-->
      <!--        :page-count="pagination.pageCount"-->
      <!--        :page-size="pagination.pageSize"-->
      <!--        :page-sizes="[10, 20, 30, 50]"-->
      <!--        :max-item-count="5"-->
      <!--        show-ellipsis-->
      <!--        show-quick-jumper-->
      <!--        show-size-picker-->
      <!--        @update:page="handlePageChange"-->
      <!--        @update:page-size="handlePageSizeChange"-->
      <!--        :size="'medium'"-->
      <!--      />-->
      <!--使用自己封装的分页组件-->
      <sg-pagination
        :current="Number(pagination.page)"
        :totalPage="Number(pagination.pageCount)"
        :size="Number(pagination.pageSize)"
        :sizeOptions="[10, 20, 30, 50]"
        theme="light"
        color="#ff5733"
        :showQuickJumper="true"
        :showSizePicker="true"
        :total-items="Number(pagination.itemCount)"
        @update:current="handlePageChange"
        @update:size="handlePageSizeChange"
      />

      <!-- 详情模态框 -->
      <n-modal v-model:show="showDetailsModal" title="接口详情" :style="{ width: '600px' }">
        <n-descriptions>
          <n-descriptions-item label="接口ID">{{ selectedInterface.id }}</n-descriptions-item>
          <n-descriptions-item label="名称">{{ selectedInterface.name }}</n-descriptions-item>
          <n-descriptions-item label="URL">{{ selectedInterface.url }}</n-descriptions-item>
          <n-descriptions-item label="请求方式">{{ selectedInterface.method }}</n-descriptions-item>
          <n-descriptions-item label="价格">{{ selectedInterface.price }}</n-descriptions-item>
          <n-descriptions-item label="描述">{{
            selectedInterface.description
          }}</n-descriptions-item>
          <n-descriptions-item label="请求头">{{
            selectedInterface.requestHeader
          }}</n-descriptions-item>
          <n-descriptions-item label="响应头">{{
            selectedInterface.responseHeader
          }}</n-descriptions-item>
          <n-descriptions-item label="状态">{{
            selectedInterface.status === 1 ? '上线' : '下线'
          }}</n-descriptions-item>
          <n-descriptions-item label="创建时间">{{
            selectedInterface.createTime
          }}</n-descriptions-item>
          <n-descriptions-item label="更新时间">{{
            selectedInterface.updateTime
          }}</n-descriptions-item>
          <n-descriptions-item label="访问次数">{{
            selectedInterface.visitedCount
          }}</n-descriptions-item>
          <n-descriptions-item label="标签">
            <n-tag v-for="tag in selectedInterface.interfaceLabelList" :key="tag">{{ tag }}</n-tag>
          </n-descriptions-item>
        </n-descriptions>
      </n-modal>

      <!-- 上传接口模态框 -->
      <!-- 上传接口模态框 -->
      <n-modal
        v-model:show="showUploadModal"
        title="上传接口"
        :style="{
          width: '600px',
          padding: '20px',
          backgroundColor: '#fff',
          boxShadow: '0 2px 12px rgba(0, 0, 0, 0.1)'
        }"
      >
        <n-space vertical>
          <h2 style="text-align: center; margin-bottom: 20px">上传接口</h2>
          <n-form ref="uploadFormRef" label-placement="left" label-width="80px">
            <!-- 表单内容 -->
            <n-form-item label="接口名称" path="name">
              <n-input v-model="uploadForm.name" placeholder="请输入接口名称" />
            </n-form-item>
            <n-form-item label="URL" path="url">
              <n-input v-model="uploadForm.url" placeholder="请输入接口URL" />
            </n-form-item>
            <n-form-item label="请求方式" path="method">
              <n-select
                v-model="uploadForm.method"
                :options="methodOptions"
                placeholder="选择请求方式"
              />
            </n-form-item>
            <n-form-item label="描述" path="description">
              <n-input
                type="textarea"
                v-model="uploadForm.description"
                placeholder="请输入接口描述"
              />
            </n-form-item>
            <n-form-item label="参数说明" path="requestParams">
              <n-input
                type="textarea"
                v-model="uploadForm.paramText"
                placeholder="请输入参数说明，支持Markdown格式"
              />
            </n-form-item>
            <n-form-item label="上传图片" path="image">
              <n-upload
                v-model:file-list="uploadForm.image"
                :max="1"
                :on-finish="handleImageUpload"
                accept="image/*"
                list-type="image-card"
              >
                <n-button>点击上传图片</n-button>
              </n-upload>
            </n-form-item>
            <n-form-item label="标签" path="interfaceLabelIdList">
              <n-select
                v-model="uploadForm.interfaceLabelIdList"
                :options="labelOptions"
                multiple
                placeholder="选择标签"
              />
            </n-form-item>
          </n-form>
          <!-- 底部按钮 -->
          <n-space justify="end" style="margin-top: 20px">
            <n-button @click="showUploadModal = false">取消</n-button>
            <n-button type="primary" @click="submitUploadForm">上传</n-button>
          </n-space>
        </n-space>
      </n-modal>
    </n-space>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, h } from 'vue'
import {
  NInput,
  NSelect,
  NButton,
  NCard,
  NDataTable,
  NTag,
  NSpace,
  NModal,
  NDescriptions,
  NDescriptionsItem,
  NPagination,
  useMessage
} from 'naive-ui'
import apiClient from '@/api/axios'
import SgPagination from '@/components/common/SgPagination.vue'

export default defineComponent({
  components: { SgPagination, NPagination },
  setup() {
    const message = useMessage()
    const searchQuery = ref('')
    const filters = reactive({
      status: null,
      creator: null
    })
    const interfaceData = reactive({
      records: [],
      total: 0
    })
    const pagination = reactive({
      page: 1,
      pageSize: 10,
      pageCount: 1,
      itemCount: 0
    })
    const loading = ref(false)
    const showDetailsModal = ref(false)
    const selectedInterface = reactive({
      id: '',
      name: '',
      price: '',
      description: '',
      url: '',
      requestHeader: '',
      responseHeader: '',
      status: 0,
      method: '',
      userId: '',
      createTime: '',
      updateTime: '',
      visitedCount: '',
      interfaceLabelList: []
    })

    const statusOptions = [
      { label: '全部', value: null },
      { label: '上线', value: 1 },
      { label: '下线', value: 0 }
    ]

    const creatorOptions = [
      { label: '全部', value: null },
      { label: '用户A', value: 'userA' },
      { label: '用户B', value: 'userB' }
      // 动态加载用户选项
    ]

    const columns = [
      { title: '接口ID', key: 'id', width: 150 },
      { title: '接口名称', key: 'name', width: 200 },
      { title: '接口URL', key: 'url', width: 250 },
      { title: '请求方式', key: 'method', width: 120 },
      { title: '创建时间', key: 'createTime', width: 180 },
      {
        title: '状态',
        key: 'status',
        width: 100,
        render(row) {
          return h(
            NTag,
            { type: row.status === 1 ? 'success' : 'warning' },
            { default: () => (row.status === 1 ? '上线' : '下线') }
          )
        }
      },
      {
        title: '操作',
        key: 'actions',
        width: 250,
        render(row) {
          return h(NSpace, null, {
            default: () => [
              h(
                NButton,
                { type: 'info', onClick: () => viewDetails(row) },
                { default: () => '详情' }
              ),
              h(
                NButton,
                { type: 'success', onClick: () => changeStatus(row, 1) },
                { default: () => '上线' }
              ),
              h(
                NButton,
                { type: 'error', onClick: () => changeStatus(row, 0) },
                { default: () => '下线' }
              ),
              h(
                NButton,
                { type: 'warning', onClick: () => editInterface(row) },
                { default: () => '编辑' }
              )
            ]
          })
        }
      }
    ]

    const fetchInterfaceData = async () => {
      loading.value = true
      try {
        const response = await apiClient.post('/interfaceInfo/list/page', {
          name: searchQuery.value,
          status: filters.status,
          pageSize: pagination.pageSize,
          current: pagination.page,
          sortField: 'createTime',
          sortOrder: 'descend'
        })
        const data = response.data.data
        interfaceData.records = data.records || []
        pagination.page = data.current || 1
        pagination.pageSize = data.size || 10
        pagination.pageCount = data.pages || 1
        pagination.itemCount = data.total || 0
      } catch (error) {
        console.error('获取接口数据失败', error)
        interfaceData.records = []
        pagination.page = 1
        pagination.pageCount = 1
        pagination.itemCount = 0
      } finally {
        loading.value = false
      }
    }

    const handlePageChange = (page: number) => {
      pagination.page = page
      fetchInterfaceData()
    }

    const handlePageSizeChange = (pageSize: number) => {
      pagination.pageSize = pageSize
      fetchInterfaceData()
    }

    const resetFilters = () => {
      searchQuery.value = ''
      filters.status = null
      filters.creator = null
      fetchInterfaceData()
    }

    const changeStatus = async (row: any, status: number) => {
      // 假设有接口来更新状态，这里简化为直接修改状态
      row.status = status
      fetchInterfaceData()
    }

    const viewDetails = (row: any) => {
      Object.assign(selectedInterface, row)
      showDetailsModal.value = true
    }

    const editInterface = (row: any) => {
      // 编辑接口逻辑，弹出编辑表单或跳转到编辑页面
      message.info(`编辑接口：${row.name}`)
    }

    const uploadInterface = () => {
      // 上传接口的逻辑，这里暂时是占位
      // message.info('上传接口功能即将推出')
      showUploadModal.value = true
      fetchLabelOptions()
    }

    onMounted(() => {
      fetchInterfaceData()
    })

    // ////////////////////上传接口代码
    const showUploadModal = ref(false)
    const uploadFormRef = ref(null)
    const uploadForm = reactive({
      name: '',
      url: '',
      method: '',
      description: '',
      paramText: '',
      image: [],
      interfaceLabelIdList: []
    })

    const methodOptions = [
      { label: 'GET', value: 'get' },
      { label: 'POST', value: 'post' },
      { label: 'PUT', value: 'put' },
      { label: 'DELETE', value: 'delete' }
    ]

    const labelOptions = ref([])

    /**
     * 拉取标签数据
     */
    const fetchLabelOptions = async () => {
      try {
        const response = await apiClient.get('/label/all')
        // 先检查响应体是否有数据
        // console.log('API Response:', response)
        if (response.data && Array.isArray(response.data)) {
          labelOptions.value = response.data.map((label: any) => ({
            label: label.labelName, // 假设字段名为 name
            value: label.id,
            ...label
          }))
        } else {
          console.error('标签数据格式不正确', response.data)
          message.error('标签数据格式不正确')
        }
      } catch (error) {
        console.error('获取标签数据失败', error)
        message.error('获取标签数据失败')
      }
    }

    const handleImageUpload = ({ file }: { file: any }) => {
      uploadForm.image = file
    }

    const submitUploadForm = async () => {
      try {
        console.log("上传接口前看看数据:uploadForm" + JSON.stringify(uploadForm))
        const formData = new FormData()
        formData.append('name', uploadForm.name)
        formData.append('url', uploadForm.url)
        formData.append('method', uploadForm.method)
        formData.append('description', uploadForm.description)
        formData.append('paramText', uploadForm.paramText)
        formData.append('interfaceLabelIdList', JSON.stringify(uploadForm.interfaceLabelIdList))
        if (uploadForm.image.length > 0) {
          formData.append('image', uploadForm.image[0].file)
        }

        const response = await apiClient.post('/interfaceInfo/add', formData)
        message.success('接口上传成功')
        showUploadModal.value = false
        await fetchInterfaceData()
      } catch (error) {
        console.error('上传接口失败', error)
        message.error('上传接口失败')
      }
    }

    //////////////////////上传接口js代码结束

    return {
      searchQuery,
      filters,
      interfaceData,
      pagination,
      loading,
      showDetailsModal,
      selectedInterface,
      statusOptions,
      creatorOptions,
      columns,
      fetchInterfaceData,
      handlePageChange,
      handlePageSizeChange,
      resetFilters,
      changeStatus,
      viewDetails,
      editInterface,
      uploadInterface,

      showUploadModal,
      uploadForm,
      uploadFormRef,
      methodOptions,
      labelOptions,
      handleImageUpload,
      submitUploadForm
    }
  }
})
</script>

<style scoped>
.interface-management {
  padding: 20px;
}

.n-card {
  margin-bottom: 20px;
}

.n-data-table {
  margin-top: 20px;
}

.n-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.n-modal {
  background-color: #fff; /* 设置背景色为白色 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}
</style>
